//
//  PHAsset.swift
//  RNAsmanMaster
//
//  Created by 李旭峰 on 10/24/19.
//  Copyright © 2019 Facebook. All rights reserved.
//

import Foundation
import Photos

extension PHAsset {
  @objc func getAVAssetAsync(complete:@escaping (AVAsset?) -> Void) {
      DispatchQueue.global().async {
          if self.mediaType != .video {
              complete(nil)
          }
          let options = PHVideoRequestOptions()
          options.version = .current
          options.isNetworkAccessAllowed = true
          options.deliveryMode = .automatic
          let imageManager = PHImageManager.default()
          imageManager.requestAVAsset(forVideo: self, options: options) {[weak self] (avAsset, audioMix, info) in
              guard let `self` = self else { return }
              DispatchQueue.main.async {
                  complete(avAsset)
              }
          }
      }
  }
  @objc func getPreviewImage(size:CGSize)-> UIImage? {
      var img:UIImage?
      let options = PHImageRequestOptions()
      options.deliveryMode = .fastFormat
      options.isSynchronous = true
      PHImageManager.default().requestImage(for: self, targetSize: size, contentMode: .aspectFill, options: options) {
          image,infoDict in
          img = image
      }
      return img
  }
  @objc func getImageAsync(complete:@escaping (UIImage?) -> Void) {
      let options = PHImageRequestOptions()
      options.deliveryMode = .highQualityFormat
      PHImageManager.default().requestImage(for: self, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFit, options: options) {[weak self]
          image,infoDict in
        guard let `self` = self else { return }
        if let tempImage = image {
          complete(tempImage)
        }else{
          var size = UIScreen.main.compatibleBounds.size
          size = CGSize(width: size.width / 3.0 , height: size.height / 3.0)
          complete(self.getPreviewImage(size: size))
        }
      }
  }
}
